package org.altervista.cp.thinjdbc.wrappers;

import java.io.PrintWriter;
import java.sql.SQLException;

import org.altervista.cp.thinjdbc.util.LogHelper;

public abstract class DataSource extends Wrapper<javax.sql.DataSource>
		implements javax.sql.DataSource {

	private static final LogHelper logger = new LogHelper(DataSource.class);

	public static final DataSource newInstance(javax.sql.DataSource ds) {
		return _GENERATOR.generate(ds);
	}

	public Connection getConnection() {
		try {
			return Connection.newInstance(unwrap().getConnection(), this);
		} catch (SQLException e) {
			throw new SQLRuntimeException(e);
		}
	}

	public Connection getConnection(String username, String password) {
		try {
			return Connection.newInstance(unwrap().getConnection(username,
					password), this);
		} catch (SQLException e) {
			throw new SQLRuntimeException(e);
		}
	}

	public int getRetriesOnError() {
		return _retriesOnError;
	}

	public void setRetriesOnError(int retriesOnError) {
		_retriesOnError = retriesOnError;
	}

	public void shutdown() {
		_GENERATOR.release(this);
	}

	void rewrap(Connection cw) {
		try {
			try {
				logger.debug("Releasing connection to the wrapped datasource");
				cw.unwrap().close();
			} catch (SQLException e) {
			}
		} finally {
			try {
				cw.wrap(unwrap().getConnection());
			} catch (SQLException e) {
				throw new SQLRuntimeException(e);
			}
		}
	}

	public abstract int getLoginTimeout();

	public abstract PrintWriter getLogWriter();

	public abstract void setLoginTimeout(int seconds);

	public abstract void setLogWriter(PrintWriter out);

	private int _retriesOnError;

	private static final _ProxyGenerator<DataSource> _GENERATOR = new _ProxyGenerator<DataSource>(
			DataSource.class);
}
